/***** BEGIN LICENSE BLOCK *****
 Version: MPL 1.1
 
 The contents of this file are subject to the Mozilla Public License Version 
 1.1 (the "License"); you may not use this file except in compliance with 
 the License. You may obtain a copy of the License at 
 http://www.mozilla.org/MPL/
 
 Software distributed under the License is distributed on an "AS IS" basis,
 WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 for the specific language governing rights and limitations under the
 License.
 
 The Original Code is GureGipuzkoa Extension.
 
 The Initial Developer of the Original Code is Asier Sarasua Garmendia.
 Portions created by the Initial Developer are Copyright (C) 2010
 the Initial Developer. All Rights Reserved.
 
 Contributor(s):
    Asier Sarasua Garmendia <asier.sarasua@gmail.com>
    Julen Ruiz Aizpuru <julenx@gmail.com>
    Juanan Pereira Varela <juanan@diariolinux.com>
 
 ***** END LICENSE BLOCK *****/


const ggPhotosets = {
 
  populateSets:
    function(i) {
      if (i == 2) {
        var userId = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.user.id");
        var aTree = document.getElementById("gg-photosets-list");
        var aTreechild = document.getElementById("gg-photoset-ch");

        aTree.view.selection.select(-1);

        //First, remove all the children of the tree
        while (aTreechild.firstChild) {
          aTreechild.removeChild(aTreechild.firstChild);
        }

        if (userId == "") {
          document.getElementById("gg-tabbox").selectedIndex=1;
          gureGipuzkoaUIUtils.prompt.alert(null,
                                 gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                                 gureGipuzkoaStrUtils.strBundle.getString("SetsNoUser"));
          ggAccounts.onLogin();
        }

        //XMLHttpRequest for photosets
        gureGipuzkoa.apiCall(
          {method: 'gg.photosets.getList', 'user_id': userId},
          function(xhr) {
            var userLang = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.lang.default");

            var nPhotosets = xhr.responseXML.getElementsByTagName("photoset");

            //If there is no photoset...
            if (nPhotosets[0] == null) {
              var it = document.createElement("treeitem");
              aTreechild.appendChild(it);
              var rw = document.createElement("treerow");
              it.appendChild(rw);
              var cl1 = document.createElement("treecell"); 
              rw.appendChild(cl1);
              msg = gureGipuzkoaStrUtils.strBundle.getString("NoSets");
              cl1.setAttribute('label', msg);
              document.getElementById("ggSidebar").removeAttribute('wait-cursor'); //Remove wait cursor
              return;
            }

            for (var i = 0; i < nPhotosets.length; i++) {
              if (userLang == "es") {
                var aTitle = nPhotosets[i].childNodes[1].textContent;
                if (aTitle == "") {
                  aTitle = nPhotosets[i].childNodes[5].textContent;
                }
              } else {
                var aTitle = nPhotosets[i].childNodes[5].textContent;
                if (aTitle == "") {
                  aTitle = nPhotosets[i].childNodes[1].textContent;
                }
              }

              var nPhotos = nPhotosets[i].attributes[2].value;
              var id = nPhotosets[i].attributes[0].value;

              var it = document.createElement("treeitem");
              aTreechild.appendChild(it);
              var rw = document.createElement("treerow");
              it.appendChild(rw);
              var cl1 = document.createElement("treecell");
              rw.appendChild(cl1);
              cl1.setAttribute('label', aTitle);  
              var cl2 = document.createElement("treecell");
              rw.appendChild(cl2);
              cl2.setAttribute('label', nPhotos);
              var cl3 = document.createElement("treecell");
              rw.appendChild(cl3);
              cl3.setAttribute('label', id);
            }

            aTree.focus();
            aTree.view.selection.select(0);
          },
        function() {});
     }
  },

  populateSet:
    function(obj) {
      var userId = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.user.id");
      var pTree = document.getElementById("gg-photosets-list");
      var aTree = document.getElementById("gg-photosets-photo");
      var aTreechild = document.getElementById("gg-photo-ch");
      var setId = pTree.view.getCellText(pTree.currentIndex, aTree.columns.getColumnAt(2));
      var perPage = gureGipuzkoaUtils.prefManager.getIntPref("guregipuzkoa.page.photocount");
      var pageNum = gureGipuzkoaUtils.prefManager.getIntPref("guregipuzkoa.photoset.currentpage");

      //First, remove all the children of the tree
      while (aTreechild.firstChild) {
        aTreechild.removeChild(aTreechild.firstChild);
      }

      if (obj.id == "gg-photoset-next-page") {
        pageNum = pageNum + 1;
      } else if (obj.id == "gg-photoset-prev-page") {
        pageNum = pageNum - 1;
      } else {
        pageNum = 1;
      }
      gureGipuzkoaUtils.prefManager.setIntPref("guregipuzkoa.photoset.currentpage", pageNum);

      //XMLHttpRequest for photoset photos
      gureGipuzkoa.apiCall(
        {method: 'gg.photosets.getPhotos', 'user_id': userId, 'photoset_id': setId, 'per_page': perPage, 'page': pageNum},
        function(xhr) {
          var userLang = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.lang.default");

          //Pagination
          var numPhotos = xhr.responseXML.getElementsByTagName("photoset")[0];
          var aPrev = document.getElementById("gg-photoset-prev-page");
          var aNext = document.getElementById("gg-photoset-next-page");
          var aCurrent = document.getElementById("gg-photoset-current-page");
          gureGipuzkoaUIUtils.paginate(numPhotos.attributes[2].value, numPhotos.attributes[4].value, aPrev, aNext, aCurrent);

          //Get the IDs of the photos
          var nPhotos = xhr.responseXML.getElementsByTagName("photo");
          var nIds = "";
          for (var i = 0; i < nPhotos.length; i++) {
            nIds = nPhotos[i].attributes[0].value;
            gureGipuzkoa.apiCall(
              {method: 'gg.photos.getInfo', 'photo_id': nIds},
              function(xhr) {

                var userLang = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.lang.default");
                var aPhoto = xhr.responseXML.getElementsByTagName("photo")[0];
                var aId = aPhoto.attributes[0].value;
                var aPdate = aPhoto.attributes[5].value;
                var aAuthor = aPhoto.attributes[9].value;
                var aUrl = xhr.responseXML.getElementsByTagName("url")[0].firstChild.data;;

                if (userLang == "es") {
                  var aTitle = aPhoto.childNodes[1].textContent;
                  if (aTitle == "") {
                    aTitle = aPhoto.childNodes[5].textContent;
                  }
                } else {
                  var aTitle = aPhoto.childNodes[5].textContent;
                  if (aTitle == "") {
                    aTitle = aPhoto.childNodes[1].textContent;
                  }
                }
                if (aTitle == "") {
                  aTitle = gureGipuzkoaStrUtils.strBundle.getString("NoTitle");
                }

                var it = document.createElement("treeitem");
                aTreechild.appendChild(it);
                var rw = document.createElement("treerow");
                it.appendChild(rw);
                var cl1 = document.createElement("treecell");
                rw.appendChild(cl1);
                cl1.setAttribute('label', aTitle);
                var cl2 = document.createElement("treecell");
                rw.appendChild(cl2);
                cl2.setAttribute('label', aId);  
                var cl3 = document.createElement("treecell");
                rw.appendChild(cl3);
                cl3.setAttribute('label', aPdate);
                var cl4 = document.createElement("treecell");
                rw.appendChild(cl4);
                cl4.setAttribute('label', aAuthor);
                var cl5 = document.createElement("treecell");
                rw.appendChild(cl5);
                cl5.setAttribute('label', aUrl);

                ggPhotosets.selectPhoto(aId, nIds);

              },
            function() {});

          }

        },
      function() {});

    },


  selectPhoto:
    function(aId, nIds) {
      if (aId == nIds) {
        document.getElementById("gg-photosets-photo").view.selection.select(0); 
      }
  },

  loadImage:        //Load thumbnail in the image and texts (author, title, description) in the labels 
    function() {
      if (gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.user.apikey") == "") {
        gureGipuzkoaUIUtils.prompt.alert(null,
                               gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                               gureGipuzkoaStrUtils.strBundle.getString("APINo"));
        gureGipuzkoa.openHelp("chrome://guregipuzkoa/locale/help/apikey.html");
        return false;
      }

      var aTree = document.getElementById("gg-photosets-photo");
      var aImage = document.getElementById("gg-photoset-thumb-image");
      aImage.src = "";
      var titleLabel = document.getElementById("gg-photoset-thumb-title");
      var selection = aTree.view.selection;
      var aUrl = aTree.view.getCellText(aTree.currentIndex, aTree.columns.getColumnAt(4));
      var aTitle = aTree.view.getCellText(aTree.currentIndex, aTree.columns.getColumnAt(0));

      aUrl = aUrl.replace(/original/, "medium");
      aImage.src = aUrl;

      titleLabel.value = "";
      titleLabel.collapsed = false;
      titleLabel.value = aTitle;

      },

  openImage:        //Open image in a tab when double clicking the thumbnail or the tree value
    function() {
      var aTree = document.getElementById("gg-photosets-photo");
      var selection = aTree.view.selection;
      //Change this
      var aUrl = gureGipuzkoa.photoURL+
                 aTree.view.getCellText(aTree.currentIndex, aTree.columns.getColumnAt(1));
      gureGipuzkoaUIUtils.useTab(aUrl);
      aTree.focus();
    },

}
